<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区-->
    <el-card>
      <!--添加一行-->
      <el-row>
        <!--添加角色-->
        <el-col>
          <el-button type="primary" @click="addRolesDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!--表格内容-->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bd-bottom', index1 === 0 ? 'bd-top' : '', 'vcenter']"
            >
              <!--一级权限-->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row, item1.id)">{{
                  item1["authName"]
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--二级权限-->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 !== 0 ? 'bd-top' : '', 'vcenter']"
                >
                  <!--二级权限-->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2["authName"] }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--三级权限-->
                  <el-col :span="13">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3["authName"] }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="角色描述" prop="roleDesc" />
        <el-table-column label="角色操作" width="300px">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolesInfo(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRolesById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--添加角色弹窗-->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesDialogClose"
    >
      <!--主体区域-->
      <el-form
        :model="addRolesForm"
        label-width="100px"
        :rules="addRolesRules"
        ref="addRolesRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesForm.roleDesc" />
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑角色弹窗-->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
    >
      <!--主体区域-->
      <el-form
        :model="editRolesForm"
        label-width="100px"
        :rules="addRolesRules"
        ref="editRolesRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRolesForm.roleDesc" />
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="checkEditForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的弹窗 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addRolesRequest,
  editRolesInfo,
  queryRolesInfo,
  removeRightById,
  removeRolesById,
  rolesListRequest,
  rightsListRequest,
  setRolesRights,
} from "../../network/power";

export default {
  name: "Roles",
  data() {
    return {
      // 角色列表
      rolesList: [],
      addRolesDialogVisible: false,
      editRolesDialogVisible: false,
      setRightDialogVisible: false,
      // 添加角色的表单对象
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      // 修改角色的表单对象
      editRolesForm: {},
      // 添加角色的验证规则
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      // 保存权限数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认勾选的节点id
      defKeys: [],
      roleId: ''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 请求角色数据
    getRolesList() {
      rolesListRequest()
        .then((res) => {
          // console.log(res)
          this.rolesList = res.data;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("获取角色列表失败");
        });
    },
    // 点击添加角色的回调
    addRolesDialog() {
      this.addRolesDialogVisible = true;
    },
    // 弹窗关闭
    addRolesDialogClose() {
      this.$refs.addRolesRef.resetFields();
    },
    // 表单预验证
    addRoles() {
      this.$refs.addRolesRef.validate((valid) => {
        if (!valid) return;
        addRolesRequest(this.addRolesForm)
          .then((res) => {
            console.log(res);
            console.log(this.rolesList);
            this.addRolesDialogVisible = false;
            this.getRolesList();
            this.$message.success(res["meta"].msg);
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("添加失败");
          });
      });
    },
    // 点击修改的回调
    editRolesInfo(id) {
      queryRolesInfo(id)
        .then((res) => {
          // console.log(res)
          this.editRolesForm = res.data;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("查询失败");
        });
      this.editRolesDialogVisible = true;
    },
    // 修改表单预校验
    checkEditForm() {
      console.log(this.editRolesForm);
      this.$refs.editRolesRef.validate((valid) => {
        if (!valid) return;
        editRolesInfo(this.editRolesForm)
          .then((res) => {
            this.getRolesList();
            this.editRolesDialogVisible = false;
            console.log(res);
            this.$message.success("修改成功");
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("修改失败");
          });
      });
    },
    // 删除角色
    removeRolesById(id) {
      // console.log(id)
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeRolesById(id)
            .then((res) => {
              this.getRolesList();
              console.log(res);
              this.$message.success(res["meta"].msg);
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 删除权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeRightById(role.id, rightId)
            .then((res) => {
              // console.log(res)
              role.children = res.data;
              this.$message.success(res["meta"].msg);
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 分配权限的对话框
    showSetRightDialog(role) {
      this.roleId = role.id
      // 清空数组，防止一直往里面push
      this.defKeys = [];
      // 获取三级权限id
      this.getNodeId(role, this.defKeys);
      rightsListRequest("tree").then((res) => {
        // console.log(res);
        this.rightsList = res.data;
      });
      this.setRightDialogVisible = true;
    },
    // 通过递归，获取三级权限id
    getNodeId(node, arr) {
      // 判断节点是否有子节点（三级权限没有）
      if (!node.children) return arr.push(node.id);
      node.children.forEach((item) => {
        this.getNodeId(item, arr);
      });
    },
    // 分配权限dialog关闭时
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 分配权限dialog确定的回调
    allotRights() {
      const keys = [
        [this.$refs.treeRef.getCheckedKeys()],
        [this.$refs.treeRef.getHalfCheckedNodes()]
      ];
      const idStr = keys.join(',')
      // console.log(idStr);
      setRolesRights(this.roleId, idStr).then((res) => {
        this.setRightDialogVisible = false
        // console.log(res);
        this.getRolesList()
        this.$message.success(res.meta.msg)

      }).catch((err) => {
        console.log(err);
      });
    },

  },
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}

.bd-top {
  border-top: 1px solid #eee;
}

.bd-bottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>